package com.hw.dagl.service.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import com.hw.dagl.dao.impl.MenuDaoImpl;
import com.hw.dagl.model.Sys_Menu;
import com.hw.dagl.service.MenuService;
import com.hw.dao.utils.EntityTools;
import com.hw.dao.utils.OraclePageDaoBase;

@Service
public class MenuServiceImpl implements MenuService {
	
	@Resource
	private MenuDaoImpl menuDaoImpl;
	@Resource
	private OraclePageDaoBase oraclePageDaoBase;
	
	
	/**
	 * 根据角色编号 查询该角色的菜单 
	 * @param rid
	 * @param isBuild 是否组装成树
	 * @return
	 */
	@Override
	public List<Sys_Menu> findRoleMenuByRid(String rid,boolean isBuild) {
		List<Sys_Menu> nodeList = new ArrayList<Sys_Menu>();
		List<Sys_Menu> list=new ArrayList<Sys_Menu>();
		list=findRoleMenuByRidSql(rid);
		if(isBuild){
			String parentId = "0";
			ConvertNodeForSwptTCd(parentId,list,nodeList);
			return nodeList;
		}else{
			return list;
		}
	}
	/*
	 * 根据角色编号 查询该角色的菜单
	 */
	@Override
	public List<Sys_Menu> findRoleMenuByRidSql(String rid){
		String sql;
		if(rid.equals("1001")){
			sql = " select * from Sys_Menu cd ";
		}else{
			sql = " select * from Sys_Menu cd "
					+ " LEFT JOIN SYS_ROLE_REF_MENU gn ON gn.mid = cd.mid WHERE 1 = 1 ";
			if(StringUtils.isNotEmpty(rid) && !("null".equals(rid))) {
				sql += " AND  gn.rid = "+rid; 
			}
		}
		sql+=" order by cdpx asc ";
		List<Sys_Menu> list=new ArrayList<Sys_Menu>();
		list=oraclePageDaoBase.query(sql, new Object[]{},new RowMapper<Sys_Menu>(){
			private EntityTools<Sys_Menu> et = new EntityTools<Sys_Menu>();
			@Override
			public Sys_Menu mapRow(ResultSet rs, int index)
					throws SQLException {
				Sys_Menu menu = new Sys_Menu();
				et.setColumnsValueByResultSet(rs, menu);
				return menu;
			}
		});
		return list;
	}
	
	//递归方法
	private void ConvertNodeForSwptTCd(String parentId,List<Sys_Menu> list,List<Sys_Menu> nodeList) {
		for (Sys_Menu t : list) {
			if(parentId.equals(t.getParentid())) {
				ArrayList<Sys_Menu> childlist = new ArrayList<Sys_Menu>();
				t.setChild(childlist); 
				ConvertNodeForSwptTCd(t.getMid(),list,childlist);
				nodeList.add(t);
			}
		}
	}
	
	public String findNavigation(String menuId){
		String menuLevelNames =  menuDaoImpl.findNavigation(menuId);
		if(StringUtils.isNotEmpty(menuLevelNames)){
			menuLevelNames = StringUtils.replace(menuLevelNames, ",", "->");
			return menuLevelNames;
		}
		return "";
	}
}
